package com.itWaiLong.Service.Impl;

import com.itWaiLong.AppException.AppException;
import com.itWaiLong.AppException.GlobalExceptionHandler;
import com.itWaiLong.Dao.User;
import com.itWaiLong.Mapper.UserMapper;
import com.itWaiLong.Service.UserService;
import com.itWaiLong.Utils.Md5Utils;
import com.itWaiLong.Utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 该类用于实现用户登录/注册的业务逻辑
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserByUserName(String username) {
        return userMapper.findUserByName(username);
    }

    @Override
    public int addUser(User user) {

        //设置用户注册的时间
        user.setRegisterTime(LocalDateTime.now());

        //对密码进行加密
        Md5Utils md5Utils = new Md5Utils();
        String rePassword = Md5Utils.getMd5(user.getPassword());
        user.setPassword(rePassword);

        return userMapper.addUser(user);
    }

    @Override
    public int updateUserInfo(User user) {

        //获取用户id
        Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
        int userId = (int) map.get("userId");
        user.setUserId(userId);

        return userMapper.updateUserInfo(user);
    }

    @Override
    public int deleteUserInfo() {

        //获取用户id
        Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
        int userId = (int) map.get("userId");

        //判断用户是否存在
        User user = userMapper.findUserByUserId(userId);
        if (user == null) {
            return -1;
        }

        return userMapper.deleteUserInfo(user.getUsername());
    }

    /**
     * 查找用户自己的信息
     * @return
     */
    public User selectUserById() {

        //获取用户id
        Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
        int userId = (int) map.get("userId");
        User user = userMapper.findUserByUserId(userId);
        return user;
    }

    @Override
    public List<User> selectAllUser() {
        List<User> users = userMapper.selectAllUser();
        if (users == null || users.size() == 0) {
            throw new GlobalExceptionHandler(AppException.YONG_HU_BU_CUN_ZAI);
        }
        return users;
    }
}
